package com.chain.BrotherExchange.ui.core;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatDelegate;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;


public abstract class BaseFragment extends Fragment {

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    private View mRootView;
    private boolean isHiddenChanged;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(getLayoutID(), container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRootView = view;
        ButterKnife.bind(this, view);

        // 初始化事件总线
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        initActions();
        savedInstanceState(savedInstanceState);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        onVisible();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (isHiddenChanged){
            onVisible();
        }

        isHiddenChanged = !isHiddenChanged;
    }

    /**
     * 初始化事件总线
     */
    protected boolean useEventBus() {
        return false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 可见时回调
     */
    protected void onVisible(){
        setStatusBar(getActivity());
    }

    protected abstract @LayoutRes int getLayoutID();

    protected abstract void initActions();

    protected void savedInstanceState(Bundle savedInstanceState){}

    protected void setStatusBar(Activity activity) {}

    protected <T extends View> T findViewById(@IdRes int id){
        return mRootView.findViewById(id);
    }
}
